package org.cuatrovientos.erp.dao;
/**
 * 
 */


import java.util.List;

import org.cuatrovientos.erp.model.Customer;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


/**
 * implementation of CustomerDAOInterface
 * @author VB
 *
 */
public class CustomerDAO implements CustomerDAOInterface {

	@Autowired
	 private SessionFactory sessionFactory;
	

	/**
	 * default constructor
	 */
	public CustomerDAO () {
		
	}
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	
	/* 
	 * selects one customer by Id
	 * @param id
	 * @return customer
	 */
	 @Transactional(readOnly = true)
	public Customer selectById(int id) {
		 Customer customer = (Customer) getSession().get(Customer.class, id);
	    return customer;
	}

	/*
	 * retrieves all customers from db
	 * @return List of customers
	 */
	 @Transactional(readOnly = true)
	 public List<Customer> selectAll() {
	 
	    List<Customer> customers = getSession().createQuery("from Customer").list();
	    return customers;
	}
	
	/*
	 * retrieves all customers from db
	 * @return List of customers
	 */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
	    List<Customer> customers = getSession().createQuery("from Customer").list();
	    return customers.size();
	}

	/*
	 * inserts a new customer in database
	 * retrieves generated id and sets to customer instance
	 * @param new product
	 */
	 @Transactional
	public void insert(Customer customer) {
	    Integer id = (Integer) getSession().save(customer);
	    customer.setId(id);           
	}

	/*
	 * updates customer
	 * @param customer to update
	 */
	 @Transactional
	public void update(Customer customer) {
		getSession().merge(customer);
	}

	/*
	 * delete given customer
	 * @param customer to delete
	 */
	 @Transactional
	public void delete(Customer customer) {
		getSession().delete(customer);
	}

	 @Transactional
	public void saveOrUpdate(Customer customer) {

		getSession().saveOrUpdate(customer);
		
	}

	 /**
	  * deletes using id
	  */
	 @Transactional
	public void deleteById(int id) {
		 Customer customer = (Customer) getSession().load(Customer.class,id);
		 getSession().delete(customer);
	}

	 /**
	  * performs search operation
	  */
	 @Transactional(readOnly = true)
	public List<Customer> search(String name) {
		   Query query = getSession().createQuery("from Customer s where s.name like :name");
           query.setParameter("name", "%"+name+"%");
           
           List<Customer> names = query.list();
		
           return names;
	}

}
